/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.worker.http;

import org.openislands.oi.pojo.base.BeanBuilder;
import org.openislands.oi.worker.app.NodeService;
import org.openislands.oi.pojo.dto.NodeDTO;
import org.openislands.oi.pojo.dto.RouteDTO;
import org.openislands.oi.pojo.qo.NodeVerifyQO;
import org.openislands.oi.pojo.vo.CommonResponse;
import org.openislands.oi.pojo.vo.NodeRouteVO;
import org.openislands.oi.pojo.vo.NodeVO;
import org.openislands.oi.util.ValueCopyUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@SuppressWarnings("unused")
@RestController
@RequestMapping("/v1/nodes")
public class NodeController {
    @Resource(type = NodeService.class)
    private NodeService nodeService;

    @PutMapping("/ping")
    public CommonResponse<Boolean> ping() {
        return CommonResponse.success(true);
    }

    @PutMapping("/verify")
    public CommonResponse<NodeVO> nodeVerify(@Validated @RequestBody NodeVerifyQO nodeVerifyQO) {
        final NodeDTO nodeDTO = ValueCopyUtils.copyProperties(nodeVerifyQO, new NodeDTO(), (source, target) -> {
            target.setRouteDTOList(source.getNodeRouteList().stream()
                    .map((nodeRouteQO) -> ValueCopyUtils.copyProperties(nodeRouteQO, new RouteDTO()))
                    .collect(Collectors.toList())
            );
            return target;
        });
        NodeDTO selfDTO = nodeService.verifyNode(nodeDTO);
        final NodeVO nodeVO = ValueCopyUtils.copyProperties(selfDTO, new NodeVO(), (source, target) -> {
            target.setNodeRouteList(source.getRouteDTOList().stream()
                    .map((nodeRouteDTO) -> ValueCopyUtils.copyProperties(nodeRouteDTO, new NodeRouteVO()))
                    .collect(Collectors.toList())
            );
            return target;
        });
        return CommonResponse.success(nodeVO);
    }

    @PutMapping("/{nodeId}/break")
    public CommonResponse<Boolean> nodeBreak(@PathVariable(value = "nodeId") String nodeId) {
        Boolean bool = nodeService.breakNode(BeanBuilder.create(new NodeDTO()).set(NodeDTO::setNodeId, nodeId).build());
        return CommonResponse.success(bool);
    }
}
